﻿var xmlreader = require("xmlreader");
var fs = require("fs");
var crypto = require("crypto");
var path = require("path");
var moment = require("moment");
const keys = require('./keys');
const db = require('../db/db');
var NodeRSA = require('node-rsa');
var jwt = require('jsonwebtoken');
let config = require('../config');

var util = {
    randomWord: function (randomFlag, min, max) {
        var str = "",
            range = min,
            arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

        // 随机产生
        if (randomFlag) {
            range = Math.round(Math.random() * (max - min)) + min;
        }
        for (var i = 0; i < range; i++) {
            pos = Math.round(Math.random() * (arr.length - 1));
            str += arr[pos];
        }
        return str;
    },
    getip: function (req) {
        var ip = req.headers['x-real-ip'] ? req.headers['x-real-ip'] : req.ip.replace(/::ffff:/, '')
        return ip;
    },
    getCountDays: function () {
        var curDate = new Date();
        /* 获取当前月份 */
        var curMonth = curDate.getMonth();
        /*  生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
        curDate.setMonth(curMonth + 1);
        /* 将日期设置为0, 这里为什么要这样设置, 我不知道原因, 这是从网上学来的 */
        curDate.setDate(0);
        /* 返回当月的天数 */
        return curDate.getDate();
    },
    wxsign: function (ret, key) {
        var newkey = Object.keys(ret).sort();
        var sign = "";
        for (var i = 0; i < newkey.length; i++) {
            //向新创建的对象中按照排好的顺序依次增加键值对
            if (newkey[i] != null && newkey[i] != 0 && newkey[i] != "sign" && newkey[i] != "key") {

                sign += newkey[i] + "=" + ret[newkey[i]] + "&";
            }

        }
        sign = sign.substring(0, sign.length - 1);
        sign = sign + "&key=" + key;
        sign = crypto.createHash('md5').update(sign).digest('hex').toUpperCase();
        return sign;
    },
    wxsign2: function (ret) {
        var newkey = Object.keys(ret).sort();
        var sign = "";
        for (var i = 0; i < newkey.length; i++) {
            //向新创建的对象中按照排好的顺序依次增加键值对
            if (newkey[i] != null && newkey[i] != 0 && newkey[i] != "sign" && newkey[i] != "key") {

                sign += newkey[i] + "=" + ret[newkey[i]] + "&";
            }
        }
        sign = sign.substring(0, sign.length - 1);
        const a_private_key = new NodeRSA(keys.privKey);
        const signature = a_private_key.sign(sign, 'base64', 'utf8');
        return signature;

    },
    wxsign3: function (ret) {
        var newkey = Object.keys(ret).sort();
        var sign = "";
        for (var i = 0; i < newkey.length; i++) {
            //向新创建的对象中按照排好的顺序依次增加键值对
            if (newkey[i] != null && newkey[i] != 0 && newkey[i] != "sign" && newkey[i] != "key") {

                sign += newkey[i] + "=" + ret[newkey[i]] + "&";
            }
        }
        sign = sign.substring(0, sign.length - 1);
        const a_private_key = new NodeRSA(keys.pingtaikey);
        const signature = a_private_key.sign(sign, 'base64', 'utf8');
        return signature;

    },
    dateformat: function (unixtimestamp) {
        var unixtimestamp = new Date(unixtimestamp * 1000);
        var year = 1900 + unixtimestamp.getYear();
        var month = "0" + (unixtimestamp.getMonth() + 1);
        var date = "0" + unixtimestamp.getDate();
        var hour = "0" + unixtimestamp.getHours();
        var minute = "0" + unixtimestamp.getMinutes();
        var second = "0" + unixtimestamp.getSeconds();
        return year + "-" + month.substring(month.length - 2, month.length) + "-" + date.substring(date.length - 2, date.length)
            + " " + hour.substring(hour.length - 2, hour.length) + ":"
            + minute.substring(minute.length - 2, minute.length) + ":"
            + second.substring(second.length - 2, second.length);
    },
    uniq: function (array) {
        var temp = []; //一个新的临时数组
        for (var i = 0; i < array.length; i++) {
            if (temp.indexOf(array[i]) == -1) {
                temp.push(array[i]);
            }
        }
        return temp;
    },
    getuserinfo(token) {

        return new Promise((resolve, reject) => {
            jwt.verify(token, config.token.secretOrPrivateKey, function (err, data) {
                // console.log("jwt", err, data);
                if (!err) {
                    resolve(data)

                } else {
                    resolve(null);
                }
            });


        })

    },
    checktoken: function (req, res, next) {
        //  console.log("rq.headers", rq.headers);
        var token = req.body.token;
        console.log("token" + token);
        jwt.verify(token, config.token.secretOrPrivateKey, function (err, decoded) {
            if (err) {
                // 返回错误信息
                res.send({
                    status: 401,
                    success: false,
                    message: 'token效验失败' + err
                });
                return;
            } else {
                // 解析必要的数据（相应字段为定义token时的字段）
                //    console.log(decoded);
                // 跳出中间件
                return next();
            }
        });
    },
    isDuringDate: function (beginDateStr, endDateStr) {
        var curDate = new Date(),
            beginDate = new Date(beginDateStr),
            endDate = new Date(endDateStr);
        if (curDate >= beginDate && curDate <= endDate) {
            return true;
        }
        return false;
    }
    , getnum: function (j) {
        var random_no = "";
        for (var i = 0; i < j; i++) //j位随机数，用以加在时间戳后面。
        {
            random_no += Math.floor(Math.random() * 10);
        }
        random_no = new Date().getTime() + random_no;
        return random_no;
    },
    getconfig() {

        var file = path.join(__dirname, '../config/config.json');
        if (fs.existsSync(file)) {
            var ss = fs.readFileSync(file);
            var str = {};
            if (ss != "") {
                str = JSON.parse(ss);
            }

            return str;

        } else {
            return null;
        }
    },
    sha_256_crypto(r_method, r_url, r_time, s_key, j_str) {
        const hash_cryptoer = crypto.createHash('sha256');
        hash_cryptoer.update(r_method)
            .update('\n')
            .update(r_url)
            .update('\n')
            .update(r_time)
            .update('\n')
            .update(s_key)
            .update('\n')
            .update(j_str);

        return hash_cryptoer.digest('hex');
    },
    PrefixInteger(num, m) {
        return (Array(m).join(0) + num).slice(-m);
    },
    async getordernum() {

        var id = "";
        var firstobj = await db.query("select * from ordernum where day='" + moment().format("YYMMDD") + "' order by id desc", []);
        if (firstobj.length > 0) {
            var first = firstobj[0];
            id = (parseInt(first.ordernum) + 1) + "";
        } else {
            id = "819801";
        }
        var ss = await db.execute("insert into ordernum(ordernum,day) values(?,?)", [id, moment().format("YYMMDD")])
        return moment().format("YYMMDD") + id;

    },
    encrypt(text) {
        var algorithm = "aes-128-cbc";
        var key = crypto.randomBytes(16);
        var iv = crypto.randomBytes(16);
        let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
        let encrypted = cipher.update(text);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        return { iv: iv.toString("hex"), encryptedData: encrypted.toString('hex') };
    },
    decrypt(text) {
        let iv = Buffer.from(text.iv, 'hex');
        let encryptedText = Buffer.from(text.encryptedData, 'hex');
        let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv);
        let decrypted = decipher.update(encryptedText);
        decrypted = Buffer.concat([decrypted, decipher.final()]);
        return decrypted.toString();
    },
    rsa(key,data) {
       
        const nodersa = new NodeRSA(key);
        // nodersa.setOptions({ encryptionScheme: 'pkcs1' });
        const encrypted = nodersa.encrypt(data, 'base64');
        return encrypted;
    }





}

module.exports = util;
